package com.srwl.mytx.activity;

import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.srwl.mytx.R;
import com.srwl.mytx.tao.av.FileUtils;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.IDUtils;
import com.srwl.mytx.utils.IMFileTools;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.ChoiceCoverView;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

//import wseemann.media.FFmpegMediaMetadataRetriever;

public class VideoCoverSelectActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "VideoCoverSelectActivit";
    private SurfaceView sv_video;
    private SurfaceHolder mSurfaceHolder;
    private MediaPlayer mMediaPlayer;
    private String videoPath;
    private ImageView iv_back;
    private Animation anim_playbutton;
    private ImageView iv_playbutton;
    private Handler mSafeHandler;
    private boolean isErrorVideo = false;
    public boolean mUploading = false;
    private boolean isSaving = false;

    private ImageView mImgCover;
    private Bitmap mCoverBitmap;
    private boolean mPubSuccess;
    private int mVideoSize;
    private final SurfaceHolder.Callback surfaceCallback;
    private Button btn_commit;
    private MediaMetadataRetriever retriever;
    private LinearLayout llCoverContainer;
    private ChoiceCoverView choiceCoverView;
    private int selectTime;
    private Bitmap selectCover;


    public VideoCoverSelectActivity() {
        surfaceCallback = new SurfaceHolder.Callback() {
            public void surfaceCreated(SurfaceHolder holder) {
                mSurfaceHolder = holder;
                initVideo();
                startVideo();
            }

            public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
            }

            public void surfaceDestroyed(SurfaceHolder holder) {
                mSurfaceHolder = null;
                stopVideo();
            }
        };
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle bundle = getIntent().getExtras();
        videoPath = bundle.getString("videoPath");
        //mVideoSize = bundle.getInt("videoSize");
        // mTempFramePicPath = bundle.getString("framePicPath");
        // mVideoDuration = bundle.getInt("videoDuration");
        //mFramePicWidth = bundle.getInt("framePicWidth");
        // mFramePicHeight = bundle.getInt("framePicHeight");
        //mUploadID = bundle.getString("uploadID");
        // mUploadTarget = bundle.getString("uploadTarget");
        if (TextUtils.isEmpty(videoPath)) {
            finish();
        }
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_video_cover_select);
        sv_video = findViewById(R.id.sv_video);
        sv_video.setOnClickListener(this);
        mSurfaceHolder = sv_video.getHolder();
        mSurfaceHolder.addCallback(surfaceCallback);
        mSurfaceHolder.setType(3);
        mSafeHandler = new Handler();
        iv_back = findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);
        iv_playbutton = findViewById(R.id.iv_playbutton);
        iv_playbutton.setVisibility(View.GONE);
        mImgCover = findViewById(R.id.img_cover);
        llCoverContainer = findViewById(R.id.ll_cover_container);
        choiceCoverView = findViewById(R.id.cover_view);
        retriever = new MediaMetadataRetriever();
        retriever.setDataSource(videoPath);
//        FFmpegMediaMetadataRetriever mmr = new FFmpegMediaMetadataRetriever();
//        mmr.setDataSource(videoPath);
//        String len = mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_DURATION);

        String len = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
        Log.i(TAG, "onCreate: retriever获取视频时长：" + len);
        long fileLength = TextUtils.isEmpty(len) ? 0 : Long.valueOf(len); //毫秒
        choiceCoverView.setOnScrollBorderListener(new ChoiceCoverView.OnScrollBorderListener() {
            @Override
            public void OnScrollBorder(float start, float end) {
                selectTime = (int) ((start + (end - start) / 2) / screenWidth * fileLength);
                Log.i(TAG, "OnScrollBorder:slelectTime: " + selectTime);
                if (!mMediaPlayer.isPlaying()) {
                    mMediaPlayer.pause();
                }
                if (!mImgCover.isShown()) {
                    mImgCover.setVisibility(View.VISIBLE);
                }
                //Bitmap frame = mmr.getFrameAtTime(selectTime * 1000, FFmpegMediaMetadataRetriever.OPTION_CLOSEST_SYNC);
                Bitmap frame = retriever.getFrameAtTime(selectTime * 1000, MediaMetadataRetriever.OPTION_CLOSEST_SYNC); //参数是微秒
                mImgCover.setImageBitmap(frame);
                selectCover = frame;
                Log.d(TAG, "OnScrollBorder: 所选图片尺寸：" + selectCover.getRowBytes() * selectCover.getHeight() / 1000);
            }

            @Override
            public void onScrollStateChange() {
                Log.i(TAG, "onScrollStateChange: 滑动状态改变");
//                mMediaPlayer.pause();
//                mMediaPlayer.seekTo(selectTime);
            }
        });
        //  rv_cover = findViewById(R.id.rv_cover);

        long increase = fileLength / 10; //生成10张图片
        int width = screenWidth / 10;
        int height = Utils.dpToPx(70, this);
        long increaseMiddle = (increase / 2);
        for (long i = increaseMiddle; i < fileLength; i += increase) {
            Log.i(TAG, "onCreate: index   " + i);
            // Bitmap frame = mmr.getFrameAtTime(i*1000, FFmpegMediaMetadataRetriever.OPTION_CLOSEST_SYNC);
            Bitmap frame = retriever.getFrameAtTime(i * 1000, MediaMetadataRetriever.OPTION_CLOSEST_SYNC); //参数是微秒
            ImageView ivCover = new ImageView(this);
            ivCover.setScaleType(ImageView.ScaleType.CENTER_CROP);
            ivCover.setImageBitmap(frame);
            llCoverContainer.addView(ivCover, width, height);
            //默认将第张获取的图片作为封面图片
            if (i == increaseMiddle) {
                selectCover = frame;
            }
            Log.d(TAG, "onCreate: 所选图片尺寸：" + selectCover.getRowBytes() * selectCover.getHeight() / 1000);
        }


        //mCoverBitmap = ThumbnailUtils.createVideoThumbnail(videoPath, 1);
//            mImgCover.setImageBitmap(mCoverBitmap);
        //Glide.with(this).load(videoPath).into(mImgCover);
        GlideLoadUtils.glideLoad(this, videoPath, mImgCover);

        // tv_previewok = (TextView)findViewById(R.id.tv_previewok);
        // tv_previewok.setOnClickListener(this);
        // changeStyle();
        btn_commit = findViewById(R.id.btn_commit);
        btn_commit.setOnClickListener(this);

    }


    private void initVideo() {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setAudioStreamType(3);
        mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            public boolean onError(MediaPlayer mp, int what, int extra) {
                finishVideo();
                stopVideo();
                isErrorVideo = true;
                showToast(getString(R.string.taorecorder_videoerror));
                return false;
            }
        });
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            public void onCompletion(MediaPlayer mp) {
                mMediaPlayer.seekTo(0);
                mMediaPlayer.start();
            }
        });
        mMediaPlayer.setDisplay(mSurfaceHolder);

        try {
            mMediaPlayer.setDataSource(videoPath);
            mMediaPlayer.prepare();
        } catch (IllegalArgumentException var2) {
            var2.printStackTrace();
        } catch (SecurityException var3) {
            var3.printStackTrace();
        } catch (IllegalStateException var4) {
            var4.printStackTrace();
        } catch (IOException var5) {
            var5.printStackTrace();
        }

        if (anim_playbutton == null) {
            anim_playbutton = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.taorecorder_alpha_hide);
            anim_playbutton.setAnimationListener(new Animation.AnimationListener() {
                public void onAnimationStart(Animation animation) {
                }

                public void onAnimationEnd(Animation animation) {
                    if (!isErrorVideo) {
                        iv_playbutton.setVisibility(View.GONE);
                    }

                }

                public void onAnimationRepeat(Animation animation) {
                }
            });
        }

    }

    public void startVideo() {
        mMediaPlayer.start();
        iv_playbutton.setVisibility(View.GONE);
        mImgCover.setVisibility(View.GONE);
        iv_playbutton.startAnimation(anim_playbutton);
    }

    public void pauseVideo() {
        if (mMediaPlayer != null && iv_playbutton != null) {
            mMediaPlayer.pause();
            iv_playbutton.setVisibility(View.VISIBLE);
        }
    }

    public void finishVideo() {
        mImgCover.setVisibility(View.VISIBLE);
        iv_playbutton.setVisibility(View.VISIBLE);
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }

    private void stopVideo() {
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }

        if (iv_playbutton != null) {
            iv_playbutton.setVisibility(View.VISIBLE);
        }

    }

    public void onResume() {
        super.onResume();
//        IMCommitManager.pageAppear(this);
    }

    public void onPause() {
        super.onPause();
//        IMCommitManager.pageDisappear(this);
    }

    protected void onDestroy() {
        stopVideo();
//        if (mRecorderManager != null) {
//            mRecorderManager.destroy();
//        }

        if (mCoverBitmap != null && !mCoverBitmap.isRecycled()) {
            mCoverBitmap.recycle();
        }

        super.onDestroy();
    }

    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.iv_back:
                finish();
                break;

            case R.id.sv_video:
                if (isErrorVideo || mMediaPlayer == null) {
                    showToast(getString(R.string.taorecorder_videoerror));
                    return;
                }

                if (mMediaPlayer.isPlaying()) {
                    pauseVideo();
                } else {
                    startVideo();
                }
                break;
            case R.id.btn_commit:
                if (isErrorVideo) {
                    showToast(getString(R.string.taorecorder_videoerror));
                    return;
                }

                if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
                    pauseVideo();
                }

                publish();

        }

    }

    public void finish() {
        if (mPubSuccess) {
            setResult(RESULT_OK, getIntent());
        } else {
            setResult(0, getIntent());
        }

        super.finish();
    }

    private void publish() {
        stopVideo();
        mPubSuccess = true;
        String dir = this.getExternalCacheDir().getAbsolutePath();
        String UUIDString = IDUtils.genUUID();
        String coverJpgPath = dir + File.separator + "short_video" + File.separator + UUIDString + ".jpg";
        getIntent().putExtra("coverPath", coverJpgPath);
        IMFileTools.writeBitmap(coverJpgPath, selectCover, 100);
        // 把视频文件复制一份，并替换掉intent 中的视频文件地址
        String videoName = IDUtils.genUUID();
        final String targetVideoPath = dir + File.separator + videoName + "_output.mp4";
        FileUtils.copyFile(videoPath, targetVideoPath);
        getIntent().putExtra("videoPath", targetVideoPath);
        finish();
    }

    private Bitmap getVideoThumb(String path, long time) {


        return retriever.getFrameAtTime(time);
    }


}
